/**
 * 存储数据到localStorage
 *
 * @param {string} key 键
 * @param {any} value 值
 */
export const lsSetItem = (key, value) => {
  // 将数组、对象类型的数据转化为 JSON 字符串进行存储
  if (typeof value === 'object') {
    value = JSON.stringify(value);
  }
  window.localStorage.setItem(key, value);
};

/**
 * 从localStorage读取数据
 *
 * @param {string} key 键
 * @returns value值
 */
export const lsGetItem = (key) => {
  const data = window.localStorage.getItem(key) ?? '';
  try {
    return JSON.parse(data);
  } catch (err) {
    return data;
  }
};

/**
 * 从localStorage中删除某条数据
 *
 * @param {string} key 键
 */
export const lsRemoveItem = (key) => {
  window.localStorage.removeItem(key);
};

/**
 * 清空localStorage
 */
export const lsRemoveAllItem = () => {
  window.localStorage.clear();
};

/**
 * 设置cookie
 *
 * @param {string} cname 键
 * @param {string} cvalue 值
 * @param {number} exdays 过期天数
 */
export function setCookie(cname, cvalue, exdays) {
  const d = new Date();
  d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
  const expires = 'expires=' + d.toGMTString();
  document.cookie = cname + '=' + cvalue + '; ' + expires;
}

/**
 * 获取某个cookie值
 *
 * @param {string} cname 键
 * @returns 存储的cookie值
 */
export function getCookie(cname) {
  const name = cname + '=';
  const ca = document.cookie.split(';');
  for (let i = 0; i < ca.length; i++) {
    const c = ca[i].trim();
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return '';
}

/**
 * 检查是否有对应的 cookie 值
 *
 * @param {string} cname 键
 * @returns 是否有对应的cookie值
 */
export function checkCookie(cname) {
  const cValue = getCookie(cname);
  if (cValue != '') {
    return true;
  }

  return false;
}
